<template>
  <div class="image-uploader">
    <h3 class="uploader-title">导入{{ typeTitle }}
      <p @click="dwMoban">下载{{ typeTitle }}模板</p>
    </h3>
    <el-upload
      class="upload-area"
      :file-list="fileList"
      :limit="limit"
      action="#"
      :auto-upload="false"
      :drag="true"
      :http-request="handleUpload"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-exceed="() => { ElMessage.warning(`最多只能上传${limit}个文件!`) }"
      ref="uploadRef"
    >
      <div class="upload-content">
        <el-icon class="upload-icon"><Box /></el-icon>
        <div class="upload-text">点击或将文件拖到此处上传</div>
      </div>
      <template #tip>
        <div class="upload-tip">请上传Excel格式的{{ typeTitle }}信息表</div>
      </template>
    </el-upload>

    <div class="action-buttons">
      <el-button @click="submitUpload" type="primary">导入</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Box } from '@element-plus/icons-vue';
import { post, uploadFile } from '@/api/request'; // 导入uploadFile函数

const uploadRef = ref(null);

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  limit: {
    type: Number,
    default: 1
  },
  fieldName: {
    type: String,
    default: 'file'
  },
  type: {
    type: String,
    default: 'student', // 默认为学生类型，可选值：student, teacher等
    validator: (value) => ['student', 'teacher'].includes(value)
  }
});

// 根据类型生成标题
const typeTitle = computed(() => {
  return props.type === 'student' ? '学生' : props.type === 'teacher' ? '教师' : '人脸';
});

const emit = defineEmits(['update:modelValue', 'on-success', 'on-cancel']);

const fileList = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

// 简化的文件移除处理
const handleRemove = (file, fileList) => {
  emit('update:modelValue', fileList || []);
};

// 简化的上传前验证，只检查是否为Excel文件
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                 file.type === 'application/vnd.ms-excel';
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false;
  }
  return true;
};

// 提交上传
const submitUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.submit();
  }
};

// 取消操作
const handleCancel = () => {
  emit('on-cancel');
  fileList.value = [];
};

// 下载模板
const dwMoban = () => {
  let templateUrl = '';

  if (props.type === 'student') {
    templateUrl = '/api/profile/file/template/学生导入模版.xlsx';
  } else if (props.type === 'teacher') {
    templateUrl = '/api/profile/file/template/教职工导入模版.xlsx';
  }

  // 创建下载链接
  const link = document.createElement('a');
  link.href = import.meta.env.VITE_API_URL + templateUrl;
  link.setAttribute('download', `${typeTitle.value}导入模版.xlsx`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  ElMessage.success(`${typeTitle.value}模板下载中...`);
};

// 处理文件导入
const handleUpload = (params) => {
  const formData = new FormData();
  console.log('Upload params:', params);
  formData.append('file', params.file);
  // formData.append('schoolId', 56);
  // formData.append('departId', '1897198566044999681');

  // 根据类型选择不同的API路径
  let apiUrl = '';
  if (props.type === 'student') {
    apiUrl = '/api/system/uis/importStudent';
  } else if (props.type === 'teacher') {
    apiUrl = '/api/system/uit/importTeacher';
  }

  // 使用封装的uploadFile函数而不是直接使用axios
  return uploadFile(apiUrl, formData)
    .then(res => {
      if (res) {
        emit('on-success', res);
        ElMessage.success(`${typeTitle.value}导入成功`);

        // 清空文件列表
        fileList.value = [];

        // 重置上传组件
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }

        // 通知父组件取消操作
        emit('on-cancel');
      } else {
        throw new Error(`导入失败：未获取到响应`);
      }
    }).catch(error => {
      console.error('导入错误：', error);
      ElMessage.error(`导入失败：` + (error.message || '未知错误'));
    });
};
</script>

<style scoped>
.image-uploader {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.uploader-title {
  text-align: left;
  width: 100%;
  margin-bottom: 15px;
  font-weight: bold;
}

.upload-area {
  width: 100%;
  border-radius: 6px;
  padding: 20px 0;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 20px;
}

.uploader-title p {
  display: inline-block;
  margin-left: 10px;
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
}
</style>
